package org.gdstash.file;

import java.io.IOException;

public abstract class GDAbstractBuffer implements GDBuffer {
    @Override
    public byte[] getByteArray(final long pos, final int length) throws IOException {
        this.setPosition(pos);
        return this.getByteArray(length);
    }

    @Override
    public byte[] getBytes8() throws IOException {
        return this.getByteArray(8);
    }

    @Override
    public long getUnsignedInt() throws IOException {
        final int i = this.getInt();
        long temp = i;
        if (i < 0) {
            temp = intToUnsignedLong(i);
        }
        return temp;
    }

    @Override
    public String getString(final int len) throws IOException {
        if (len <= 0) {
            return "";
        }
        final byte[] bytes = this.getByteArray(len);
        final StringBuilder sb = new StringBuilder(bytes.length);
        for (int i = 0; i < bytes.length; ++i) {
            sb.append((char) bytes[i]);
        }
        return sb.toString();
    }

    @Override
    public String getStringLB() throws IOException {
        final byte len = this.getByte();
        return this.getString(len);
    }

    @Override
    public String getStringNT() throws IOException {
        final StringBuilder sb = new StringBuilder(256);
        for (byte b = this.getByte(); b != 0; b = this.getByte()) {
            sb.append((char) b);
        }
        return sb.toString();
    }

    @Override
    public ARZString getARZString() throws IOException {
        final ARZString str = new ARZString();
        str.len = this.getInt();
        str.str = this.getString(str.len);
        return str;
    }

    public static String bytesToString(final byte[] bytes) {
        final StringBuilder sb = new StringBuilder(bytes.length);
        for (int i = 0; i < bytes.length; ++i) {
            sb.append((char) bytes[i]);
        }
        return sb.toString();
    }

    public static long intToUnsignedLong(final int i) {
        return (long) i & 0xFFFFFFFFL;
    }
}
